package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author : xyiaao
 * @createDate : 2022/1/28 17:15
 */
@RestControllerAdvice(annotations = {Controller.class})
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());
        if (exception.getMessage().contains(("Duplicate entry"))) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 处理CustomException异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception exception) {
        log.error(exception.getMessage());
        return R.error("系统繁忙，请稍后重试");
    }
}
